#!/bin/bash

# Ruoyi-ai Application Start Script

# 应用名称
APP_NAME="ruoyi-admin"
JAR_NAME="ruoyi-admin.jar"
APP_HOME=$(cd "$(dirname "$0")" && pwd)
JAR_PATH="$APP_HOME/target/$JAR_NAME"

# JVM 参数配置 (针对2GB内存环境优化)
JAVA_OPTS="-Xms256m -Xmx1024m"
JAVA_OPTS="$JAVA_OPTS -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true"
JAVA_OPTS="$JAVA_OPTS -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=256m"
JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC"
JAVA_OPTS="$JAVA_OPTS -Xlog:gc*:file=$APP_HOME/logs/gc.log:time,tags:filecount=3,filesize=5M"

# Redis配置
JAVA_OPTS="$JAVA_OPTS -Dspring.data.redis.port=6666"

# 创建日志目录
mkdir -p $APP_HOME/logs

# 检查应用jar包是否存在
if [ ! -f "$JAR_PATH" ]; then
  echo "Application jar not found: $JAR_PATH"
  echo "Please build the project first with 'mvn clean package'"
  exit 1
fi

# 启动应用
echo "Starting $APP_NAME..."
echo "JVM Options: $JAVA_OPTS"
echo "JAR Path: $JAR_PATH"

nohup java $JAVA_OPTS -jar $JAR_PATH > $APP_HOME/logs/startup.log 2>&1 &

# 记录进程ID
echo $! > $APP_HOME/app.pid

echo "$APP_NAME is starting in the background. PID: $(cat $APP_HOME/app.pid)"
echo "Check logs in $APP_HOME/logs/ for more details."